package www.configure.all.modules.websocket;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import www.configure.all.modules.domain.LocalProperties;


import java.net.InetSocketAddress;
import java.util.Map;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

	@Autowired
	private LocalProperties localProperties;

	@Autowired
	private RedissonClient redissonClient;

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(new StatusChangeWebsocketHandler(localProperties,redissonClient), "/statusChange")
			.addInterceptors(new CustomHandshakeInterceptor())
			.setAllowedOrigins("*");
	}

	private static class CustomHandshakeInterceptor implements HandshakeInterceptor {
		public static String getClientIp(ServerHttpRequest request) {
			String xffHeader = request.getHeaders().getFirst("X-Forwarded-For");
			if (xffHeader == null) {
				InetSocketAddress remoteAddress = request.getRemoteAddress();
				if (remoteAddress != null) {
					return remoteAddress.getAddress().getHostAddress();
				}
			} else {
				return xffHeader.split(",")[0];
			}
			return null;
		}

		@Override
		public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
			String clientIp = getClientIp(serverHttpRequest);
			map.put("clientIp", clientIp);
			return true;
		}

		@Override
		public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

		}
	}
}
